<!--
    入库订单列表组件
-->
<template>
	<div>
		<div class="e-m-t-45 flex" style="justify-content: space-between">
			<el-button @click="downloadwithdrawa()" style="margin-bottom:30px; margin-top: 1px;" type="primary" plain><i class="iconfont icon-excel"></i>导出Excel</el-button>
			<el-form :inline="true" class="demo-form-inline">
				<el-form-item>
					<el-input placeholder="关键词搜索" v-model="key" prefix-icon="el-icon-search"></el-input>
				</el-form-item>
				<!-- <el-form-item>
					<span class="other-search-show" :class="isActive ? 'is-active' : ''" @click="isActive = !isActive">
						{{ isActive ? '收起筛选' : '更多筛选' }}<i class="el-icon-arrow-down el-icon--right"></i>
					</span>
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" @click="getList(true)">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 更多筛选条件 -->
		<div class="other-search-form" :class="isActive ? 'is-active' : ''">
			<el-form label-position="left" label-width="auto" :inline="true" size="small">
				<div class="flex align-items-center">
					<!-- 时间筛选 -->
					<timeChangeList v-model="timeType" @input="getList" @change="changeTime"></timeChangeList>
				</div>
				<div class="flex align-items-center">
						<!-- <el-form-item label="订单类型" class="e-flex-1">
						<el-radio-group v-model="ordertype" size="small" @input="getList(true)">
							<el-radio-button v-for="item in options" :key="item.value" :label="item.value">{{ item.label}}</el-radio-button>
						</el-radio-group>
					</el-form-item> -->
					<div class="e-flex-1" v-if="showStoreList">
						<el-form-item label="站点筛选">
							<el-select v-model="innerStoreid" placeholder="请选择" @change="getList(true)">
								<el-option v-for="item in StoreList" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</div>
					<div class="e-flex-1">
						<el-form-item label="负责收货">
							<userList v-model="staffId" @change="(val)=>{staffId = val;getList(true)}"></userList>
						</el-form-item>
					</div>
					<div class="e-flex-1">
						<el-form-item label="负责人">
							<userList v-model="brotherId" @change="(val)=>{brotherId = val;getList(true)}"></userList>
						</el-form-item>
					</div>
				</div>
			</el-form>
		</div>
		<div class="type-state e-m-b-30">
			<span v-for="(item, index) in statusArr" :key="index" :class="{ 'on': state == item.value }" @click="getManageState(item.value)">{{ item.name }}</span>
		</div>

		<!-- 自定义表格 -->
		<custom-table
			:table-data="tableData"
			:columns="tableColumns"
			:actions="tableActions"
			:total="total"
			:page-index="pageIndex"
			:page-size="pageSize"
			:show-summary="true"
			:summary-method="getSummaries"
			@page-change="handlePagination"
			@action-click="handleTableAction"
		>
			<!-- <template #weight="scope">
				<div><span>应入：{{scope.row.userorderweight }}</span></div>
				<div><span>实入：{{scope.row.orderweight }}</span></div>
			</template>
			<template #quantity="scope">
				<div><span>应入：{{scope.row.userorderquantity }}</span></div>
				<div><span>实入：{{scope.row.orderquantity }}</span></div>
			</template>
			<template #amount="scope">
				<div><span>应入：{{scope.row.userorderamount }}</span></div>
				<div><span>实入：{{scope.row.orderamount }}</span></div>
			</template> -->
			<!-- 自定义状态 -->
			<template #state="scope">
				<span class="color-success" v-if="scope.row.state == '已入库' || scope.row.state == '已完成'">{{scope.row.state }}</span>
				<span class="color-danger" v-else-if="scope.row.state == '已取消'">{{ scope.row.state }}</span>
				<span class="color-warning" v-else>{{ scope.row.state }}</span>
			</template>
		</custom-table>

		<!-- 取消理由 -->
		<el-dialog title="取消订单" :visible.sync="showcancel" width="30%">
			<el-input type="textarea" :rows="5" placeholder="请输入取消订单的理由" v-model="textarea" maxlength="200">
			</el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showcancel = false">取消</el-button>
				<el-button type="primary" @click="cancelOrderSubmit">确定</el-button>
			</span>
		</el-dialog>
		<!-- 详情页面弹窗(小哥入库订单) -->
		<el-drawer
			title=""
			:visible.sync="viewShow.show"
			direction="rtl"
			size="80%"
			:with-header="false"
			>
			<brotherOrderViews v-if="viewShow.show" :id="viewShow.id" @goBack="viewShow.show = false"></brotherOrderViews>
		</el-drawer>
		<!-- 详情页面弹窗(线下入库订单详情) -->
		<el-drawer
			title=""
			:visible.sync="fitViewShow.show"
			direction="rtl"
			size="80%"
			:with-header="false"
			>
			<fitOrderViews v-if="fitViewShow.show" :id="fitViewShow.id" @goBack="fitViewShow.show = false"></fitOrderViews>
		</el-drawer>
	</div>
</template>

<script>
import fitOrderViews from './fitOrderViews.vue'
import brotherOrderViews from './brotherOrderViews.vue'
import timeChangeList from '@/components/form-select-type/timeChangeList.vue'
import userList from '@/components/form-select-type/userList.vue'
export default {
	name: 'storeInOrderList',
    props: {
        storeId:{
            type: Number,
            default: 0
        }
    },
	components:{
		fitOrderViews,
		brotherOrderViews,
		timeChangeList,
		userList
	},

	data() {
		return {
			// 小哥入库订单
			viewShow:{
				id: 0,
				show: false //详情页面弹窗
			},
			// 线下入库订单显示
			fitViewShow:{
				id: 0,
				show: false
			},
			// 时间类型
            timeType: 0, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
            startDate: '', //开始时间
            endDate: '', //结束时间
			ordertype: 1,
			options: [
				{
					value: 0,
					label: '全部'
				},
				{
					value: 1,
					label: '小哥入库单'
				},
				{
					value: 2,
					label: '线下单'
				}
			],
			paywayList: [
				{
					value: 0,
					label: '全部'
				},
				{
					value: 2,
					label: '现金'
				},
				{
					value: 3,
					label: '银行账户'
				},
				{
					value: 4,
					label: '支付宝'
				},
				{
					value: 5,
					label: '微信小程序'
				},
				{
					value: 1,
					label: '其他'
				},
			],
			payway: 0,
			value1: "",//下单时间
			startDate: "",//下单初始
			endDate: "",//下单结束
			loading: true,
			key: '',
			pageIndex: 1,
			pageSize: 10,
			total: 0,
			tableData: [],
			tableColumns: [
				{ 
					prop: 'number', 
					label: '订单ID'
				},
				{ 
					prop: 'ordertype', 
					label: '订单类型', 
					width: 100
				},
				{ 
					prop: 'storename', 
					label: '入库站点', 
				},
				{ 
					prop: 'staffname', 
					label: '负责收货', 
				},
				{ 
					prop: 'brothername', 
					label: '负责人', 
				},
				{ 
					prop: 'userorderweight', 
					label: '应入重量（KG）', 
					sortable: true
				},
				{ 
					prop: 'orderweight', 
					label: '实入重量（KG）', 
					sortable: true
				},
				{ 
					prop: 'userorderquantity', 
					label: '应入件数（件）', 
					sortable: true
				},
				{ 
					prop: 'orderquantity', 
					label: '实入件数（件）', 
					sortable: true
				},
				{ 
					prop: 'userorderamount', 
					label: '应入金额（元）',
					sortable: true
				},
				{ 
					prop: 'orderamount', 
					label: '实入金额（元）',
					sortable: true
				},
				{ 
					prop: 'storagetime', 
					label: '入库时间', 
					width: 180
				},
				{ 
					prop: 'state', 
					label: '订单状态',
					slotName: 'state', 
				},
				{ 
					prop: 'remarks', 
					label: '备注', 
				}
			],
			tableActions: [
				{ 
					name: 'view', 
					label: '查看',
					// visible: row => row.status !== 'deleted'
				},
				{
					name: 'cancel',
					label: '取消订单',
					visible: row => row.state == '待入库'
				}
			],
			statusArr: [
				{
					name: '全部',
					value: null
				},
				{
					name: '待入库',
					value: 0
				},
				{
					name: '已入库',
					value: 1
				},
				{
					name: '已取消',
					value: 2
				}
			],
			state: null,
			// 
			nowid: 0,
			textarea: "",
			showcancel: false,
			StoreList: '',
			innerStoreid: this.storeId,
            showStoreList: this.storeId>0?false:true,
			isActive: true, //控制更多筛选显示
			param: {},
			staffId: null,
			brotherId: null
		}
	},
	watch: {
		state(value) {
			this.getList()
		}
	},
	mounted() {
		for (let k in this.$route.query) {
			if (this.$route.query[k]) {
				if (k == 'pageIndex' || k == 'pageSize') {
					this[k] = parseInt(this.$route.query[k])
				} else if (k == 'startDate' || k == 'endDate') {
					this[k] = this.$route.query[k]
					this.value1 = [this.$route.query['startDate'], this.$route.query['endDate']]
				} else {
					this[k] = this.$route.query[k]
				}

				if (k == 'ordertype' || k == 'startDate' || k == 'endDate' || k == 'timeType' || k == 'Storeid') {
					this.isActive = true
				}
			}
		}
		this.getList()
		this.getstorelist()
	},
	methods: {
		// 翻页操作处理
		handlePagination({ pageIndex, pageSize }) {
			this.pageIndex = pageIndex
			this.pageSize = pageSize
			this.getList(false) // 获取新数据
		},
		// 操作按钮点击事件
		handleTableAction({ action, row, event }) {
			switch(action) {
				case 'view':
					this.goView(event,row)
				break
				case 'cancel':
					this.cancelOrder(row)
				break
			}
		},
		getSummaries(param) {
			// 合计
			const { columns, data } = param;
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = '合计';
					return;
				}
				const values = data.map(item => Number(item[column.property]));
				if (!values.every(value => isNaN(value))) {
					sums[index] = values.reduce((prev, curr) => {
						const value = Number(curr);
						if (!isNaN(value)) {
							return prev + curr;
						} else {
							return prev;
						}
					}, 0);
					sums[index] += '';
				} else {
					sums[index] = '';
				}

				// if (column.label == '实入金额（元）') {
				// 	sums[index] = Number(sums[index]).toFixed(2)
				// }
				// else if (column.label == '实入重量（KG）') {
				// 	sums[index] = Number(sums[index]).toFixed(2)
				// } else if (column.label == '实入件数（件）') {
				// 	sums[index] = Number(sums[index]).toFixed(2)
				// }else {
				// 	sums[index] = ''
				// }
				if (column.label == '实入金额（元）' || column.label == '实入重量（KG）' || column.label == '实入件数（件）' || column.label == '应入金额（元）' || column.label == '应入重量（KG）' || column.label == '应入件数（件）') {
					sums[index] = Number(sums[index]).toFixed(2)
				}else{
					sums[index] = ''
				}
			});

			return sums;
		},
		getstorelist() {
			this.$axios.post('/Select/StoreList', {
				"pageIndex": 1,
				"pageSize": 999,
			}).then((res) => {
				console.log(res)
				this.StoreList = res.rows
				this.StoreList.unshift({ id: 0, name: '全部' })
			}).catch((err) => {
				this.loading = false
			})
		},
		downloadwithdrawa() {
			this.$axios.post('/Store/InOrder/Download', {
				"request": {
					"pageIndex": 0,
					"pageSize": 0,
					"key": this.key,
					"state": this.state,
					"startDate": this.startDate,
					"endDate": this.endDate,
					"ordertype": this.ordertype,
					"timeType": this.timeType,
					"Storeid": this.innerStoreid,
					"staffId": this.staffId || 0,
					"brotherId": this.brotherId || 0
				},
				"fields": [
					{
						"e": "number",
						"c": "订单编号"
					},
					{
						"e": "ordertype",
						"c": "订单类型"
					},
					{
						"e": "storename",
						"c": "入库站点"
					},
					{
						"e": "staffname",
						"c": "负责收货"
					},
					{
						"e": "brothername",
						"c": "负责人"
					},
					{
						"e": "userorderweight",
						"c": "应入重量（KG）"
					},
					{
						"e": "orderweight",
						"c": "实入重量（KG）"
					},
					{
						"e": "userorderquantity",
						"c": "应入件数（件）"
					},
					{
						"e": "orderquantity",
						"c": "实入件数（件）"
					},
					{
						"e": "userorderamount",
						"c": "应入金额（元）"
					},
					{
						"e": "orderamount",
						"c": "实入金额（元）"
					},
					{
						"e": "storagetime",
						"c": "入库时间"
					},
					{
						"e": "state",
						"c": "订单状态"
					},
					{
						"e": "remarks",
						"c": "备注"
					}
				],
				downloadFileName:'入库订单'
			}, {
				responseType: 'blob'
			}).then(res => {
				console.log(res)
				let content = res;
				let fileName = '入库订单.xls'
				this.utils.saveAndExport(content, fileName)
			})
		},
		changeTime(e) {
            console.log(e)
            this.startDate = e['startDate']
            this.endDate = e['endDate']
            this.timeType = e['timeType']
            this.getList()
        },
		getManageState(val) {
			this.pageIndex = 1
			this.state = val
		},
		getList(renew = true) {
			if(renew == true){
				this.pageIndex = 1
			}
			this.tableData = []
			this.loading = true
			this.param = {
				"pageIndex": this.pageIndex,
				"pageSize": this.pageSize,
				"key": this.key,
				"state": this.state,
				"startDate": this.startDate,
				"endDate": this.endDate,
				"ordertype": this.ordertype,
				"timeType": this.timeType,
				"Storeid": this.innerStoreid,
				"staffId": this.staffId || 0,
				"brotherId": this.brotherId || 0
			}
			return this.$axios.post('/Store/InOrder/List', this.param).then((res) => {
				this.loading = false
				
				this.tableData = res.rows;
				this.total = res.total;
			}).catch((err) => {
				this.loading = false
			})
		},
		goView(event,row) {
			if (event.ctrlKey) {
				console.log('Ctrl + 左键点击');
				// 这里可以执行你需要的操作
				let param = []
				for(let k in this.param){
					if(this.param[k]){
						param.push(`${k}=${this.param[k]}`)
					}
				}
				this.$router.push(`/order/brother/list?${param.join('&')}`)
				if (row.ordertype == '小哥入库单') {
					window.open('/order/brother/Views?id=' + row.id, '_blank');
				} else {
					window.open('/order/brother/fitViews?id=' + row.id, '_blank');
				}
			} else {
				console.log('普通点击');
				if (row.ordertype == '小哥入库单') {
					this.viewShow.id = row.id
					this.viewShow.show = true
				} else {
					this.fitViewShow.id = row.id
					this.fitViewShow.show = true
				}
			}
		},
		rowClick(row){
			if (row.brother) {
				this.viewShow.id = row.id
				this.viewShow.show = true
			} else {
				this.fitViewShow.id = row.id
				this.fitViewShow.show = true
			}
		},
		pageChange(e) { // 页码切换事件
			this.pageIndex = e;
			this.getList(false)
			// this.$router.push(`/order/brother/list?p=${this.pageIndex}`)
		},
		handleSizeChange(val) {
			this.pageIndex = 1;
			this.pageSize = val;
			this.getList()
		},
		del(id) {
			return new Promise((resolve, reject) => {
				this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// this.$axios.post('/newsDetail/delete?Ids=' + id).then((res) => {
					// 	this.$message.success(res.msg);
					// 	this.getList()
					// 	resolve()
					// })
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			})
		},
		cancelOrder(id) {
			this.showcancel = true;
			this.nowid = id;
		},
		cancelOrderSubmit() {
			this.$axios.post('/Store/InOrder/Cancel', {
				id: this.nowid,
				reason: this.textarea,
			}).then((res) => {
				this.$message({
					type: 'success',
					message: res.msg
				});
				this.showcancel = false;
				this.textarea = "";
				this.getList()
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.nav-bar {
	padding: 20px 0 0;
}

.send {
	margin-top: 15px;
	margin-right: 10px;
}

.dialogForm {
	display: flex;
	flex-wrap: wrap;

	.el-form-item {
		width: 50%;
		float: left;

		&.all {
			width: 100%;
		}

		.el-select {
			width: 100%;
		}
	}
}

.user-face {
	display: flex;
	align-items: center;
	position: relative;

	.male,
	.female {
		font-size: 14px;
		position: absolute;
		left: 30px;
		top: 0;
		background-color: #fff;
		height: 16px;
		width: 16px;
		line-height: 16px;
		border-radius: 6px;
	}

	.male {
		color: var(--blue);
	}

	.female {
		color: var(--pink);
	}
}

.other-search-show {
	cursor: pointer;

	&.is-active {
		color: var(--main)
	}

	&.is-active .el-icon-arrow-down {
		transform: rotate(180deg);
	}

	.el-icon-arrow-down {
		transition: all 0.3s;
	}
}

.other-search-form {
	overflow: hidden;
	// height: 0;
	transition: all 0.3s;
	border-color: transparent;

	&.is-active {
		height: auto;
		padding: 18px;
		background: var(--light);
		border: 1px solid var(--border-light);
		padding-bottom: 0px;
		margin-bottom: 18px;
		border-radius: 4px;
		box-sizing: border-box;
	}
}
</style>
